import query from './atom/db/query';
import count from './atom/db/count';
import { IBaseTable } from './atom/db/interfaces';

declare const action_id: string;
declare const session_id: string;
declare const spaceid: string;

interface Message {
	filter: {};
	sort: {};
	page_size: number;
	page_no: number;
}

interface Train_plan extends IBaseTable {

	_id: string;
	work_plan: string;
	exec_plan_no: string;
	employ_form: string;
	deptid: string;
	deptname: string;
	staff_name: string;
	staff_number: string;
	total_people: string;
	site: string;
	org_name: string;
	contact_name: string;
	course_name: string;
	class_hour: string;
	start_time: number;
	finish_time: number;
	activity_budget: string;
	odepatment_id: string;
	resume_partment: string;
	pub_user_no: string;
	pub_user_name: string;
	branch_message: string;
	require: string;
	remark: string;
	memo: string;
	training_content: string;
	accessory_url: string;
}


function format(date: number) {
	if (date === null) {
		return '';
	}
	try {
		const _date = new Date(parseFloat(date + ''));
		if (_date) {
			return _date.getFullYear() + '-' + _format(_date.getMonth() + 1) + '-' + _format(_date.getDate());
		}
		return '';
	} catch (error) {
		return '';
	}
}

function _format(d: number) {
	if (d < 10) {
		return '0' + d;
	} else {
		return d;
	}
}

async function atom(msg: Message) {
	const systemid = '6051';
	const { exec, prepare } = query(action_id, session_id, spaceid, systemid);
	const asc: string[] = [];
	const desc: string[] = [];
	if (msg.sort) {
		const key = Object.keys(msg.sort)[0];
		if (msg.sort[key] === -1) {
			desc.push(key);
		} else {
			asc.push(key);
		}
	}
	// 证照信息
	prepare('certifi_info', [
		'_id',
		'work_plan',
		'exec_plan_no',
		'employ_form',
		'deptid',
		'deptname',
		'staff_name',
		'staff_number',
		'total_people',
		'site',
		'org_name',
		'contact_name',
		'course_name',
		'class_hour',
		'start_time',
		'finish_time',
		'activity_budget',
		'odepatment_id',
		'resume_partment',
		'pub_user_no',
		'pub_user_name',
		'branch_message',
		'require',
		'remark',
		'memo',
		'training_content',
		'accessory_url'
	], msg.filter, msg.page_size, msg.page_no, asc, desc);
	const [data] = await exec();

	data.forEach((item: Train_plan) => {
		item['start_time_str'] = format(item.start_time);
		item['finish_time_str'] = format(item.finish_time);
	});

	const c = count(action_id, session_id, spaceid, systemid);
	c.prepare('train_plan', msg.filter);
	const [t] = await c.exec();

	return { dataArray: data, count: t };
}